import time
import pyautogui
import cv2
import numpy as np
import pyperclip
from paddleocr import PaddleOCR
import pygetwindow as gw

# 初始化 PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang='ch')

def get_window_position_and_size(window_title):
    """获取窗口的位置和大小"""
    windows = gw.getWindowsWithTitle(window_title)
    if not windows:
        print(f"未找到窗口: {window_title}")
        return None
    window = windows[0]
    return window.left, window.top, window.width, window.height

def preprocess_image(image):
    """对图像进行预处理"""
    # 转换为灰度图
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 去噪
    denoised = cv2.fastNlMeansDenoising(gray, None, 30, 7, 21)

    # 二值化
    _, binary = cv2.threshold(denoised, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    # 锐化
    kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32)
    sharpened = cv2.filter2D(binary, -1, kernel)

    return sharpened

def screenshot_and_process(custom_message):
    """截取屏幕指定区域的图像并进行 OCR 识别"""
    position_size = get_window_position_and_size("NN")
    if position_size is None:
        return


    left, top, width, height = position_size
    screenshot = pyautogui.screenshot(region=(left, top, width, height))
    x_start = width - 250
    x_end = width - 30
    y_start = height - 100
    y_end = height - 50

    right_bottom_region = screenshot.crop((x_start, y_start, x_end, y_end))
    right_bottom_region_cv = cv2.cvtColor(np.array(right_bottom_region), cv2.COLOR_RGB2BGR)
    processed_region = preprocess_image(right_bottom_region_cv)

    # 使用 PaddleOCR 进行 OCR 识别
    result = ocr.ocr(processed_region, cls=True)

    # 提取识别结果
    if result and result[0]:
        for line in result[0]:
            recognized_text = line[1][0]
            print(f"识别到的文本: {recognized_text}")
            if "欢迎来到房间" in recognized_text:
                send_welcome_message(custom_message)
                break
    else:
        print("未识别到任何文本")

def send_welcome_message(custom_message):
    """发送欢迎消息"""
    pyperclip.copy(custom_message)
    pyautogui.hotkey('ctrl', 'v')
    pyautogui.press('enter')
    time.sleep(3)

# 用户输入的自定义消息
custom_message = "欢迎来到房间"

# 调用函数进行截图和处理
screenshot_and_process(custom_message)